package com.columboid.testharness.util;

import java.io.StringReader;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import com.columboid.protocol.syncml.helper.JaxbHelper;
import com.columboid.protocol.syncml.metainfo.Format;
import com.columboid.protocol.syncml.metainfo.MetInf;
import com.columboid.protocol.syncml.metainfo.NextNonce;
import com.columboid.protocol.syncml.metainfo.ObjectFactory;
import com.columboid.protocol.syncml.metainfo.Type;
import com.columboid.protocol.syncml.tests.resources.SyncMLString;

public class MetInfHandler {

	public static String getToken(String meta) {

		String xsd = JaxbHelper.getMetaSchema();
		StringReader xmlReader = new StringReader(meta);
		StringReader xsdReader = new StringReader(xsd);

		MetInf mi = null;
		try {
			mi = CreateMetInfObject(xmlReader, xsdReader);
		} catch (JAXBException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Log4j.logger.error(e.toString());
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Log4j.logger.error(e.toString());
		}
		return mi.getNextNonce().getContent();
	}

	public static MetInf CreateMetInfObject(StringReader xmlReader,
			StringReader xsdReader) throws JAXBException, SAXException {
		JAXBContext jaxbContext = JAXBContext
				.newInstance(new Class[] { ObjectFactory.class });

		SchemaFactory sf = SchemaFactory
				.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);

		Schema schema = sf.newSchema(new SAXSource(new InputSource(xsdReader)));

		Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
		unmarshaller.setSchema(schema);

		StreamSource source = new StreamSource(xmlReader);
		JAXBElement<MetInf> miElement = (JAXBElement<MetInf>) unmarshaller
				.unmarshal(source, MetInf.class);
		MetInf mi = (MetInf) miElement.getValue();
		return mi;
	}

	public static String CreateMetInfObjectStr(String Nonce) {

		MetInf meta = new MetInf();
		Format format = new Format();
		format.setContent("b64");
		meta.setFormat(format);

		Type type = new Type();
		type.setContent("syncml:auth-md5");
		meta.setType(type);

		if (Nonce != null) {
			NextNonce nextNonce = new NextNonce();
			nextNonce.setContent(Nonce);
			meta.setNextNonce(nextNonce);
		}

		try {
			return JaxbHelper.getJaxbObjectString(meta, MetInf.class, false);
		} catch (JAXBException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}

	}
}
